//
//  SHRequestManager.m
//  JiFengDaRen
//
//  Created by SH_iOS on 2018/1/30.
//  Copyright © 2018年 SH_iOS. All rights reserved.
//
#import "AFNetworkActivityIndicatorManager.h"
#import "SHCacheManager.h"
#import "SHRequestEntity.h"
#import "SHRequestManager.h"

/* 网络请求单例 */
#define   SHRequestManagerShare [SHRequestManager sharedRequestManager]

/* self 弱引用 */
#define SHWeakSelf __weak __typeof( self ) weakSelf = self

/* 用来装载网络请求任务 */
static NSMutableArray *tasks;
@interface SHRequestManager()
@property (nonatomic, strong) AFHTTPSessionManager *requestSessionManger;

@end
@implementation SHRequestManager

+ (instancetype)sharedRequestManager
{
    /*! 为单例对象创建的静态实例，置为nil，因为对象的唯一性，必须是static类型 */
    static id sharedRequestManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedRequestManager = [[super allocWithZone:NULL] init];
    });
    return sharedRequestManager;
}

+ (void)initialize
{
    [self setupRequestManager];
}



+ (void)setupRequestManager
{
     SHRequestManagerShare.requestSessionManger = [AFHTTPSessionManager manager];

    //设置请求数据格式为json
    //     XDRequestManagerShare.requestSerializer = XDHttpRequestSerializerJSON;

    //设置服务器响应数据格式为json
    //     XDRequestManagerShare.responseSerializer = XDHttpResponseSerializerJSON;


    /*! 设置请求超时时间，默认：30秒 */
    SHRequestManagerShare.timeoutInterval = 30;

    /*! 打开状态栏的等待菊花 */
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
    /*! 设置返回数据类型为 json, 分别设置请求以及相应的序列化器 */
    /*!
     根据服务器的设定不同还可以设置：
     json：[AFJSONResponseSerializer serializer](常用)
     http：[AFHTTPResponseSerializer serializer]
     */
    //    AFJSONResponseSerializer *response = [AFJSONResponseSerializer serializer];
    //    /*! 这里是去掉了键值对里空对象的键值 */
    ////    response.removesKeysWithNullValues = YES;
    //    XDRequestManagerShare.sessionManager.responseSerializer = response;

    /* 设置请求服务器数类型式为 json */
    /*!
     根据服务器的设定不同还可以设置：
     json：[AFJSONRequestSerializer serializer](常用)
     http：[AFHTTPRequestSerializer serializer]
     */
    //    AFJSONRequestSerializer *request = [AFJSONRequestSerializer serializer];
    //   XDRequestManagerShare.sessionManager.requestSerializer = request;
    /*! 设置apikey ------类似于自己应用中的tokken---此处仅仅作为测试使用*/
    //        [manager.requestSerializer setValue:apikey forHTTPHeaderField:@"apikey"];

    /*! 复杂的参数类型 需要使用json传值-设置请求内容的类型*/
    //        [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    /*! 设置响应数据的基本类型 */
    SHRequestManagerShare.requestSessionManger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"text/css", @"text/xml", @"text/plain", @"application/javascript", @"application/x-www-form-urlencoded", @"image/*", nil];

    //    XDRequestManagerShare.sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/css", @"text/xml", @"text/plain", @"application/javascript", @"application/x-www-form-urlencoded", @"image/*", nil];

    // 配置自建证书的Https请求
    //    [self setupSecurityPolicy];
}


///**
// 配置自建证书的Https请求，只需要将CA证书文件放入根目录就行

//+ (void)setupSecurityPolicy
//{
//    //    NSData *cerData = [NSData dataWithContentsOfFile:cerPath];
//    NSSet <NSData *> *cerSet = [AFSecurityPolicy certificatesInBundle:[NSBundle mainBundle]];
//
//    if (cerSet.count == 0)
//    {
//        /*!
//         采用默认的defaultPolicy就可以了. AFN默认的securityPolicy就是它, 不必另写代码. AFSecurityPolicy类中会调用苹果security.framework的机制去自行验证本次请求服务端放回的证书是否是经过正规签名.
//         */
//        AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
//        securityPolicy.allowInvalidCertificates = YES;
//        securityPolicy.validatesDomainName = NO;
//        XDRequestManagerShare.sessionManager.securityPolicy = securityPolicy;
//    }
//    else
//    {
//        /*! 自定义的CA证书配置如下： */
//        /*! 自定义security policy, 先前确保你的自定义CA证书已放入工程Bundle */
//        /*!
//         https://api.github.com网址的证书实际上是正规CADigiCert签发的, 这里把Charles的CA根证书导入系统并设为信任后, 把Charles设为该网址的SSL Proxy (相当于"中间人"), 这样通过代理访问服务器返回将是由Charles伪CA签发的证书.
//         */
//        // 使用证书验证模式
//        AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:cerSet];
//        // 如果需要验证自建证书(无效证书)，需要设置为YES
//        securityPolicy.allowInvalidCertificates = YES;
//        // 是否需要验证域名，默认为YES
//        //    securityPolicy.pinnedCertificates = [[NSSet alloc] initWithObjects:cerData, nil];
//
//        XDRequestManagerShare.sessionManager.securityPolicy = securityPolicy;
//
//
//        /*! 如果服务端使用的是正规CA签发的证书, 那么以下几行就可去掉: */
//        //            NSSet <NSData *> *cerSet = [AFSecurityPolicy certificatesInBundle:[NSBundle mainBundle]];
//        //            AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:cerSet];
//        //            policy.allowInvalidCertificates = YES;
//        //            XDRequestManagerShare.sessionManager.securityPolicy = policy;
//    }
//}


#pragma mark - url 中文格式化
+ (NSString *)strUTF8Encoding:(NSString *)str
{
    /*! ios9适配的话 打开第一个 */
    if ([[UIDevice currentDevice] systemVersion].floatValue >= 9.0)
    {
        return [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLPathAllowedCharacterSet]];
    }
    else
    {
        return [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }
}

#pragma mark - setter / getter
/**
 存储着所有的请求task数组

 @return 存储着所有的请求task数组
 */
+ (NSMutableArray *)tasks
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        SHLog(@"创建请求task数组");
        tasks = [[NSMutableArray alloc] init];
    });
    return tasks;
}

- (void)setTimeoutInterval:(NSTimeInterval)timeoutInterval
{
    _timeoutInterval = timeoutInterval;
   SHRequestManagerShare.requestSessionManger.requestSerializer.timeoutInterval = timeoutInterval;
}

- (void)setRequestSerializer:(SHHttpRequestSerializer )requestSerializer
{
    _requestSerializer = requestSerializer;
    switch (requestSerializer) {
        case SHHttpRequestSerializerJSON:
        {
             SHRequestManagerShare.requestSessionManger.requestSerializer = [AFJSONRequestSerializer serializer] ;
        }
            break;
        case SHHttpRequestSerializerHTTP:
        {
             SHRequestManagerShare.requestSessionManger.requestSerializer = [AFHTTPRequestSerializer serializer] ;
        }
            break;

        default:
            break;
    }
}

- (void)setResponseSerializer:(SHHttpResponseSerializer)responseSerializer
{
    _responseSerializer = responseSerializer;
    switch (responseSerializer) {
        case SHHttpResponseSerializerJSON:
        {
            SHRequestManagerShare.requestSessionManger.responseSerializer = [AFJSONResponseSerializer serializer] ;
        }
            break;
        case SHHttpResponseSerializerHTTP:
        {
            SHRequestManagerShare.requestSessionManger.responseSerializer = [AFHTTPResponseSerializer serializer] ;
        }
            break;

        default:
            break;
    }
}

- (void)setRequestHeader:(NSDictionary *)requestHeader
{
    _requestHeader = requestHeader;

    if (![requestHeader isKindOfClass:[NSDictionary class]])
    {
        SHLog(@"请求头数据有误，请检查！");
        return;
    }
    NSArray *keyArray = requestHeader.allKeys;

    if (keyArray.count <= 0)
    {
        SHLog(@"请求头数据有误，请检查！");
        return;
    }

    for (NSInteger i = 0; i < keyArray.count; i ++)
    {
        NSString *keyString = keyArray[i];
        NSString *valueString = requestHeader[keyString];

        [SHRequestManager setValue:valueString forHTTPHeaderKey:keyString];
    }
}

/**
 *  自定义请求头
 */
+ (void)setValue:(NSString *)value forHTTPHeaderKey:(NSString *)HTTPHeaderKey
{
    [SHRequestManagerShare.requestSessionManger.requestSerializer setValue:value forHTTPHeaderField:HTTPHeaderKey];
}


/**
 删除所有请求头
 */
+ (void)clearAuthorizationHeader
{
    [SHRequestManagerShare.requestSessionManger.requestSerializer clearAuthorizationHeader];
}

#pragma mark - 网络请求的类方法 + Entity --- get / post / put / delete

/**
 网络请求的实例方法 get
 
 @param entity  请求信息载体
 @param success 请求成功的回调
 @param failure 请求失败的回调
 @return AFHTTPRequestOperation
 */
+ (NSURLSessionTask *)GETWithEntity:(SHRequestEntity *)entity
                            success:(SHResponseSuccess)success
                            failure:(SHResponseFailure)failure
                           progress:(SHDownloadProgress)progress;


{
    if (!entity || ![entity isKindOfClass:[SHRequestEntity class]]) {
        return nil;
    }

    return [self requestWithType:SHRequestGET cache:entity.isCache encrypt:entity.isEncrypt decode:entity.isDecode urlString:entity.urlString parameters:entity.parameters success:success failure:failure progress:progress];;
}

/**
 网络请求的实例方法 post
 
 @param entity 请求信息载体
 @param successBlock 请求成功的回调
 @param failureBlock 请求失败的回调
 @param progressBlock 进度
 @return BAURLSessionTask
 */
+ (NSURLSessionTask *)POSTWithEntity:(SHRequestEntity *)entity
                             success:(SHResponseSuccess)success
                             failure:(SHResponseFailure)failure
                            progress:(SHDownloadProgress)progress;


{
    
    if (!entity || ![entity isKindOfClass:[SHRequestEntity class]]) {
        return nil;
    }
    return [self requestWithType:SHRequestPOST cache:entity.isCache encrypt:entity.isEncrypt decode:entity.isDecode urlString:entity.urlString parameters:entity.parameters success:success failure:failure progress:progress];
}

/**
 网络请求的实例方法 put
 
 @param entity 请求信息载体
 @param successBlock 请求成功的回调
 @param failureBlock 请求失败的回调
 @param progressBlock 进度
 @return BAURLSessionTask
 */
+ (NSURLSessionTask *)PUTWithEntity:(SHRequestEntity *)entity
                            success:(SHResponseSuccess)success
                            failure:(SHResponseFailure)failure
                           progress:(SHDownloadProgress)progress;


{
    if (!entity || ![entity isKindOfClass:[SHRequestEntity class]]) {
        return nil;
    }
    return [self requestWithType:SHRequestPUT cache:entity.isCache encrypt:entity.isEncrypt decode:entity.isDecode urlString:entity.urlString parameters:entity.parameters success:success failure:failure progress:progress];
}

/**
 网络请求的实例方法 delete
 
 @param entity 请求信息载体
 @param successBlock 请求成功的回调
 @param failureBlock 请求失败的回调
 @param progressBlock 进度
 @return BAURLSessionTask
 */
+ (NSURLSessionTask *)DELETEWithEntity:(SHRequestEntity *)entity
                               success:(SHResponseSuccess)success
                               failure:(SHResponseFailure)failure
                              progress:(SHDownloadProgress)progress;


{
    if (!entity || ![entity isKindOfClass:[SHRequestEntity class]]) {
        return nil;
    }
    return [self requestWithType:SHRequestDELETE cache:entity.isCache encrypt:entity.isEncrypt decode:entity.isDecode urlString:entity.urlString parameters:entity.parameters success:success failure:failure progress:progress];
}


#pragma mark - 网络请求的类方法 --- get / post / put / delete 基类
/*!
 *  网络请求的实例方法
 *
 *  @param type            get / post / put / delete
 *  @param isNeedCache     是否需要缓存，只有 get / post 请求有缓存配置
 *  @param isNeedRsaEncode 是否需要rsa加密 post put 请求body需要加密
 *  @param isNeedRsaDecode 是否需要rsa解密 返回的内容一般需要解密
 *  @param urlString       请求的地址
 *  @param parameters      请求的参数
 *  @param successBlock    请求成功的回调
 *  @param failureBlock    请求失败的回调
 *  @param progressBlock   进度
 */
+ (NSURLSessionTask *)requestWithType:(SHRequestType)type
                                cache:(BOOL)cache
                              encrypt:(BOOL)encrypt
                               decode:(BOOL)decode
                            urlString:(NSString *)urlString
                           parameters:(id)parameters
                              success:(SHResponseSuccess)success
                              failure:(SHResponseFailure)failure
                            progress:(SHDownloadProgress)progress

{

    if (urlString == nil)
    {
        return nil;
    }

    SHWeakSelf;
    /*! 检查地址中是否有中文 */
    NSString *URLString =
    [NSURL URLWithString:urlString] ? urlString : [self strUTF8Encoding:urlString];
    URLString = [BASE_URL stringByAppendingString:urlString];

    NSString *requestType;
    switch (type) {
        case SHRequestGET:
            requestType = @"GET";
            break;
        case SHRequestPOST:
            requestType = @"POST";
            break;
        case SHRequestPUT:
            requestType = @"PUT";
            break;
        case SHRequestDELETE:
            requestType = @"DELETE";
            break;

        default:
            break;
    }

    AFHTTPSessionManager *operationManager  = SHRequestManagerShare.requestSessionManger;
    
    operationManager.requestSerializer = [AFJSONRequestSerializer serializer];
    operationManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    /*
    NSTimeInterval timeoutInterval = SHRequestManagerShare.timeoutInterval;
    NSString *cacheMsg        = cache   ? @"开启缓存模式": @"关闭缓存模式";
    NSString *encryptMsg      = encrypt ? @"开启加密": @"关闭加密";
    NSString *decodeMsg       = decode  ? @"开启解密": @"关闭解密";

    CGFloat allCacheSize = [SHCacheManager sh_getAllHttpCacheSize];
   
    SHLog(@"\n******************** 请求参数 ***************************");
    SHLog(@"\n请求头: %@\n超时时间设置：%.1f 秒【默认：30秒】     \nAFHTTPRequestSerializer：%@【默认：AFJSONRequestSerializer】\nAFHTTPResponseSerializer：%@【默认：AFJSONResponseSerializer】\n请求方式: %@\n请求URL: %@\n请求param: %@\n是否启用缓存：%@【默认：开启】\n是否启用RSA加密：%@【默认：不加密】\n是否启用RSA解密：%@【默认：开启解密】\n目前总缓存大小：%.6fM\n", SHRequestManagerShare.requestSessionManger.requestSerializer.HTTPRequestHeaders, timeoutInterval, operationManager.requestSerializer, operationManager.responseSerializer, requestType, URLString, parameters, cacheMsg,encryptMsg,decodeMsg, allCacheSize);
    SHLog(@"\n********************************************************");
   */
    NSURLSessionTask *sessionTask = nil;
    // 读取缓存
    id responseCacheData =  [SHCacheManager sh_httpCacheWithUrlString:urlString parameters:parameters];
    if (cache && responseCacheData != nil)
    {//有缓存直接读取缓存数据
        
        if (success)
        {
            // 对数据进行解密
            [self decodeWithResponseObject:responseCacheData
                                    decode:decode
                               complection:^(id result) {
              success(result);
//            SHLog(@"取用缓存数据结果：\n URLString : %@ *** %@ : ",URLString,result);
            }];
        }

        [[weakSelf tasks] removeObject:sessionTask];
        return nil;
    }
    
    parameters = [self cryptWithParameters:parameters encrypt:encrypt];
    
    
    if (type == SHRequestGET)
    {
        //* AF 3.0 写法
        sessionTask = [SHRequestManagerShare.requestSessionManger GET:URLString parameters:parameters  progress:^(NSProgress * _Nonnull downloadProgress)
        {
            // 回到主线程刷新UI
            dispatch_async(dispatch_get_main_queue(), ^{
                if (progress)
                {
                    progress(downloadProgress.completedUnitCount, downloadProgress.totalUnitCount);
                }
            });
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            [self decodeWithResponseObject:responseObject
                                    decode:decode
                               complection:^(id result) {
                                   success(result);
                                   // 对数据进行异步缓存
                                   if (cache == YES) {
                                       [SHCacheManager sh_setHttpCache:responseObject urlString:urlString parameters:parameters];
                                   }
                               }];
            
            [[weakSelf tasks] removeObject:sessionTask];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            [self httpTodoPrintResponseError:error];
            
            if (failure)
            {
                failure(error);
            }
            [[weakSelf tasks] removeObject:sessionTask];
            
        }];
            
    }
    else if (type == SHRequestPOST)
    {
        //AF 3.0 写法
        sessionTask = [SHRequestManagerShare.requestSessionManger POST:URLString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
            SHLog(@"上传进度--%lld, 总进度---%lld",uploadProgress.completedUnitCount,uploadProgress.totalUnitCount);

            // 回到主线程刷新UI
            dispatch_async(dispatch_get_main_queue(), ^{
                if (progress)
                {
                    progress(uploadProgress.completedUnitCount, uploadProgress.totalUnitCount);
                }
            });
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
           
            [self decodeWithResponseObject:responseObject
                                    decode:decode
                               complection:^(id result) {
                                   success(result);
                                   // 对数据进行异步缓存
                                   if (cache == YES) {
                                       [SHCacheManager sh_setHttpCache:responseObject urlString:urlString parameters:parameters];
                                   }
                             
            }];
           
            [[weakSelf tasks] removeObject:sessionTask];

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            [self httpTodoPrintResponseError:error];

            if (failure)
            {
                failure(error);
            }
            [[weakSelf tasks] removeObject:sessionTask];

        }];
         
        
    }
    else if (type == SHRequestPUT)
    {
        // AF 3.0 写法
        sessionTask = [SHRequestManager.sharedRequestManager.requestSessionManger PUT:URLString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

            if (success)
            {
                [self decodeWithResponseObject:responseObject
                                        decode:decode
                                   complection:^(id result) {
                                       
                                       success(result);
                                       
                                   }];
                if (cache == YES) {
                    [SHCacheManager sh_setHttpCache:responseObject urlString:urlString parameters:parameters];
                }
                
            }

            [[weakSelf tasks] removeObject:sessionTask];

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {


            [self httpTodoPrintResponseError:error];

            if (failure)
            {
                failure(error);
            }
            [[weakSelf tasks] removeObject:sessionTask];

        }];
        
    }
    else if (type == SHRequestDELETE)
    {
        //AF 3.0
        sessionTask = [SHRequestManager.sharedRequestManager.requestSessionManger DELETE:URLString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (success)
            {
                success(responseObject);
            }

            [[weakSelf tasks] removeObject:sessionTask];

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

            [self httpTodoPrintResponseError:error];
            if (failure)
            {
                failure(error);
            }
            [[weakSelf tasks] removeObject:sessionTask];

        }];
        
    }

    //AF 3.0 写法
    if (sessionTask)
    {
        [[weakSelf tasks] addObject:sessionTask];
    }
   
    return sessionTask ;
}

//#pragma mark - 统一打印打印错误信息
+ (void)httpTodoPrintResponseError:(NSError *)error
{
    SHLog(@"错误信息  : \n code : %ld \n domain : %@  \n userInfo : %@ ",(long)error.code,error.domain,error.userInfo);
}


#pragma mark - 取消 Http 请求
/*!
 *  取消所有 Http 请求
 */
+ (void)cancelAllRequest
{

    // 锁操作
    @synchronized(self)
    {
        // AF 3.0写法
        [[self tasks] enumerateObjectsUsingBlock:^(NSURLSessionTask  *_Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {
            [task cancel];
        }];
        [[self tasks] removeAllObjects];
        
        
        
        [[self tasks] removeAllObjects];
    }
}

/*!
 *  取消指定 URL 的 Http 请求
 */
+ (void)cancelRequestWithURL:(NSString *)URL
{
    if (!URL)
    {
        return;
    }
    @synchronized (self)
    {
        // AF 3.0
        [[self tasks] enumerateObjectsUsingBlock:^(NSURLSessionTask  *_Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {

            if ([task.currentRequest.URL.absoluteString hasPrefix:URL])
            {
                [task cancel];
                [[self tasks] removeObject:task];
                *stop = YES;
            }
        }];
        
        
       
    }
}


- (void)clearAllHttpCache{
    
    
    
}

#pragma mark -- RSA
#pragma mark -- RSA加密body
+ (NSDictionary *)cryptWithParameters:(NSDictionary *)parameters encrypt:(BOOL)isEncrypt
{
    
    NSDictionary *requestBody;

    if (!parameters){
        
        requestBody = @{};
        return requestBody;
        
    }else{
        
        if (isEncrypt) {
            
            HBRSAHandler* handler = [HBRSAHandler  shareHandler];
            requestBody = [handler encrencryptWithDictionary:parameters];
            
        }else{
            requestBody = parameters;
        }
       
    }
    
    return  requestBody;
    
}


#pragma mark --  RSA解密

+ (void)decodeWithResponseObject:(id)responseObject decode:(BOOL)isDecode complection:(void(^)(id result))successBlock {
    
    id result = LFJson(responseObject);
    
    if (!result) {
        
        SHLog(@"返回数据JSON解析失败");
    }
    
    
    if (!isDecode) {
        successBlock(result);
        return;
    }
    HBRSAHandler* handler = [HBRSAHandler shareHandler];
    
    if ([result isKindOfClass:[NSDictionary class]] ) {
        
        BOOL  success = [result[@"success"] boolValue];
        
        if (success) {
            
            
            if (![result[@"data"] isKindOfClass:[NSDictionary class]]) {
                
                return;
                
            }
            NSDictionary *data = result[@"data"];
            if (isDecode && [data objectForKey:@"msg"] &&[data objectForKey:@"signature"] ) {//加密
                
                NSString *msg = result[@"data"][@"msg"];
                if (msg) {
                    msg = [handler decryptWithPrivatecKey:msg];
                    
                }
                
                if (([msg hasPrefix:@"{"] && [msg hasSuffix:@"}"]) || ([msg hasPrefix:@"["] && [msg hasSuffix:@"]"])){
                    
                    NSData *jsonData = [msg dataUsingEncoding:NSUTF8StringEncoding];
                    NSDictionary *msgDict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil];
                    
                    NSMutableDictionary *resultDict = [[NSMutableDictionary alloc]init];
                    [resultDict setValue:result[@"success"] forKey:@"success"];
                    [resultDict setValue:msgDict forKey:@"data"];
                    
                    successBlock(resultDict);
                    
                }else{
                    
                    successBlock(result);
                }
                
            }else{
                successBlock(result);
                
            }
            
        }else{
            
            if ([result[@"data"] isKindOfClass:[NSString class]]) {
                
                if ([result[@"data"] isEqualToString:@"relogin"]) {
                   //强制跳转到登录页面
                    
                }
                successBlock(result);
                
                
            }else{
                
                SHLog(@"返回数据格式不对！");
            }
            
        }
    }
    
}

@end
